package ffdata.scraping;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.google.common.base.Joiner;
import com.google.common.io.Files;

public class ScrapingMain {

	public static void main(String[] args) {
		// Log in first
//		WebDriver driver = logIn(Consts.getPassword(), Consts.getUsername());
//		// Get all hrefs
//		List<String> hrefs = getPlayerHrefs(driver);
		// Print hrefs in href.txt in resources
		List<String> hrefs = new ArrayList<String>();
		hrefs.add("Dinamo");
		hrefs.add("Hajduk");
		printHrefs(hrefs);
		

	}

	private static WebDriver logIn(String pass, String user) {
		// The Firefox driver supports javascript
		WebDriver driver = new FirefoxDriver();

		// Go to the Yahoo login page
		driver.get("https://login.yahoo.com/config/login?.src=spt&.intl=us&.lang=en-US");

		// Login to Yahoo profile
		// Added 5sec interval between
		try {
			driver.findElement(By.id("username")).sendKeys(user);
			Thread.sleep(5000);
			driver.findElement(By.id("passwd")).sendKeys(pass);
			Thread.sleep(5000);
			driver.findElement(By.id(".save")).submit();
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return driver;
	}

	private static List<String> getPlayerHrefs(WebDriver driver) {

		List<String> hrefList = new ArrayList<String>();
		// Go to page with all players
		driver.get(Consts.getPlayersPage());
		// Added 5sec interval between
		try {
			Thread.sleep(10000);
			// Go to advanced search
			driver.findElement(By.className("ys-adv-search")).click();
			Thread.sleep(5000);
			// click Apply
			driver.findElement(By.className("ys-advSearch-btn")).click();
			Thread.sleep(5000);

			// Get all player hrefs
			List<WebElement> anchorList = driver.findElements(By
					.className("ys-player-link"));
			// Retrieve href attribute from anchor
			for (WebElement anchor : anchorList) {
				String href = anchor.getAttribute("href");
				System.out.println(href);
				hrefList.add(href);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();

		}
		return hrefList;
	}

	private static void printHrefs(List<String> hrefs) {
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource("hrefs.txt");
			Files.write(Joiner.on("\n").join(hrefs), new File(url.toString()), StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
